package com.graph6;


import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Random;
import java.util.Set;
import java.util.concurrent.TimeUnit;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


public class GroupDemoThread {
	private static final Logger log = LoggerFactory.getLogger(GroupDemoThredPool.class);

	public static void main(String[] args) {
		Random r = new Random();
		int[][] edges = new int[10000][2];
		
		for (int[] edge : edges) {
			edge[0]=r.nextInt(9999);
			edge[1]=r.nextInt(9999);
			
		}
//		for (int[] edge : edges) {
//			System.out.println(Arrays.toString(edge));
//		}
		Arrays.sort(edges, new Comparator<int[]>() {
		    @Override
		    public int compare(int[] o1, int[] o2) {
		        return o1[0] - o2[0];
		    }
		});
		
		List<Tx> txs = new ArrayList<Tx>();
		for (int[] edge : edges) {
			txs.add(new Tx(edge[0], edge[1]));
		}
		HashMap<Integer, List<Tx>> map = new HashMap<Integer, List<Tx>>();

		int group = 0;
		while (!txs.isEmpty()) {
			Tx vertex = txs.get(0);
			Set<Integer> set = new HashSet<Integer>();
			set.add(vertex.getFrom());
			set.add(vertex.getTo());
			Iterator<Tx> iterator = txs.iterator();
			List<Tx> txadd = new ArrayList<Tx>();
			while (iterator.hasNext()) {
				Tx tx = iterator.next();
				if(set.contains(tx.getFrom())||set.contains(tx.getTo())) {
					set.add(tx.getFrom());
					set.add(tx.getTo());
					txadd.add(tx);
					iterator.remove();
				}
			}
			map.put(group, txadd);
			group++;
		}
		System.out.println("总共分组："+map.size());
		map.forEach((key, value) -> {
			new Thread(()->{

				for (Tx tx : value) {
					try {
						TimeUnit.MILLISECONDS.sleep(20);

						log.info("tx: {}", tx);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
			},"threadName:"+key).start();

		});

	}

}
